<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var lastRemaining = function (n) {
      let step = head = left = 1
      while (n > 1) {
        if (left || n % 2) head += step
        step <<= 1, n >>= 1, left = !left
      }
      return head
    };
    console.log(lastRemaining(9));
  </script>

</body>

</html>